var express = require('express');
var router = express.Router();

let { userModel, roleModel, permissionModel } = require('../model/model');
const { mongoose } = require('mongoose');
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

//用户添加
// router.post('/add', async (req, res) => {
//   await userModel.create(req.body)
//   res.send({
//     code: 200
//   })
// })

//角色添加
// router.post('/add', async (req, res) => {
//   console.log(req.body);
//   await roleModel.create(req.body)
//   res.send({
//     code: 200
//   })
// })
//权限添加
// router.post('/add', async (req, res) => {
//   await permissionModel.create(req.body)
//   res.send({
//     code: 200
//   })
// })

// 企业登录
router.post('/enterpriselogin', async (req, res) => {
  let { username, password, roleid } = req.body;
  let roleObjectid = new mongoose.Types.ObjectId(roleid)
  // 查找用户
  let user = await userModel.findOne({ username, password, role: roleObjectid });
  if (!user) {
      return res.send({ code: 400});
  }

  // 根据角色 ID 返回相应的角色信息
  let role = user.role;
  let roleinfo = await roleModel.findOne({ _id: role });
  let rolename = roleinfo.name;
  let permissions_list = await permissionsTotree(roleinfo.permissions);
  console.log(permissions_list);
  
  res.send({
      code: 200,
      user,
      role,
      rolename,
      permissions_list
  });
});


//权限整理成树形
async function permissionsTotree(rolelist) {
  let permissions = await permissionModel.find({ _id: { $in: rolelist } }).lean()
  let obj = {}
  permissions.forEach(ele => obj[ele._id] = ele)
  let list = []
  permissions.forEach((ele => {
    if (!ele['parentId']) {
      list.push(ele)
    } else {
      if (!obj[ele.parentId]) {
        obj[ele.parentId] = {};
      }
      if (!obj[ele.parentId]['children']) {
        obj[ele.parentId]['children'] = []
      }
      obj[ele.parentId]['children'].push(ele)
    }
  }))
  return list;
}

//权限树整理
router.get('/getpermission', async (req, res) => {
  let permissionList = await permissionModel.find().lean()
  let obj = {}
  permissionList.forEach(ele => obj[ele._id] = ele)
  let list = []
  permissionList.forEach((ele => {
    if (!ele['parentId']) {
      list.push(ele)
    } else {
      if (!obj[ele.parentId]) {
        obj[ele.parentId] = {};
      }
      if (!obj[ele.parentId]['children']) {
        obj[ele.parentId]['children'] = []
      }
      obj[ele.parentId]['children'].push(ele)
    }
  }))
  res.send({
    code: 200,
    data: list
  })
})

//用户登录
router.post('/userlogin', async (req, res) => {
  let { username, password } = req.body;
  let user = await userModel.findOne({ username, password })
  if (user) {
    res.send({
      code: 200
    })
  }else{
    res.send({
      code: 400
    })
  }
  
})
module.exports = router;
